const { allServices } = require('../models/mysqlConfig.js')
const verify = require('../utils/verify.js')
const ipAddress = 'http://116.62.149.160';
const sex = ['boy', 'girl']
const path = require('path')
const fs = require('fs') // 文件读写
const { port } = require('../models/defaultConfig.js')
class userService {
  async login(ctx) {
    const { username, password } = ctx.request.body
    let _sql = `select * from users where usersname="${username}";`
    let data = await allServices.query(_sql).then(async _res => {
      // console.log(_res[0]);
      if (_res.length === 0) {
        ctx.msg = '账号不存在'
        ctx.code = 401
        return false
      } else if (_res[0].userpwd !== password) {
        ctx.msg = '密码错误'
        ctx.code = 403
        return false
      } else {
        let _verify = await verify.Token(ctx.request);
        let res_ = {
          username: _res[0].usersname,
          nickname: _res[0].nickname,
          id: _res[0].id,
          email: _res[0].email,
          userPhoto: _res[0].userPhoto,
          userIntroduce: _res[0].userIntroduce,
          sex: _res[0].sex,
          oldPassword: null,
          newPassword: null
        }
        // console.log(res_);
        // res.setHeader('authorization',_verify)//两个参数都必须为字符串，不可以是变量
        return { res: res_, token: _verify }
      }

    }).catch(res => {
      Promise.reject(res);
    })
    return data
  }
  async register(ctx) {
    const { username, password } = ctx.request.body
    let _sql = `select usersname from users where usersname='${username}'`
    let data = await allServices.query(_sql).then(async _res => {
      if (_res.length > 0) {
        ctx.flag = false
        ctx.code = 402
        ctx.msg = '账号已被注册'
        return false
      } else {
        _sql = `insert into users set ?`
        return await allServices.query(_sql, { usersname: username, userpwd: password, nickname: `用户${username}`, userPhoto: `${ipAddress}:${port}/${sex[Math.floor(Math.random() * 2)]}.jpg`, sex: null, email: null, userIntroduce: null }).then(_res => {
          if (_res.insertId) {
            ctx.msg = '注册成功'
            return true
          } else return
        })
      }
    })
    return data
  }
  async uploadImg(ctx) {
    // console.log(ctx.request.files.f1);
    let files = ctx.request.files ? ctx.request.files.f1 : [] // 找前端传过来的f1
    let body = ctx.request.body // 简写
    let result = []
    let fileToken = body.token // 前端传过来的时间戳
    let fileIndex = body.index // 前端传过来的下标
    if (files && !Array.isArray(files)) {
      files = [files] //如果不是数组,将files变成数组
    }
    files && files.forEach(item => {
      let path = item.path.replace(/\\/g, '/') // 正则，将例如C:\workspace 转化为 C:/workspace
      // let fname = item.name  // 拿到每一项的名字 blob
      let nextPath = path.slice(0, path.lastIndexOf('/') + 1) + fileIndex + '-' + fileToken; // 下一个路径
      if (item.size > 0 && path) {
        fs.renameSync(path, nextPath) // 改路径的名字。改成自己取的名字 例如  C:/workspace/js/bigFile/server/public/upload_1e387a3f62851216089e83f4c1a5181b' 改成 C:/workspace/js/bigFile/server/public/Index-fileToken;
        result.push(nextPath.slice(nextPath.lastIndexOf('/') + 1))// 截取文件片段名字
      }
    })

    // 合并文件片段
    if (body.type === 'merge') {
      let filename = body.filename //拿到最后一次传过来的参数，包含文件名字
      let chunkCount = body.chunkCount // 拿到总数
      let folder = path.resolve(__dirname, '../public') + '/'; // 拿到路径
      let writeStram = fs.createWriteStream(`${folder}${filename}`) //创建出写文件的流,接受的参数是文件的路径
      console.log(`${folder}${filename}`);
      let cindex = 0
      // 合并
      const fnMergeFile = () => {
        let fname = `${folder}${cindex}-${fileToken}`;
        let readStream = fs.createReadStream(fname); // 读文件流
        readStream.pipe(writeStram, { end: false }) // 会自己去找相关的文件，然后将其合并到第一个参数里边去，如果文件不完整，则会抛出错误
        readStream.on('end', () => {
          fs.unlink(fname, (err) => {//错误捕获
            if (err) {
              throw err
            }
          })
          if (cindex + 1 < chunkCount) {
            cindex += 1
            fnMergeFile()
          }
        })
      }
      fnMergeFile()
      ctx.msg = '上传成功'
      return {
        imgPath: `${ipAddress}:${port}/${filename}`
      }
    } else {
      ctx.code = 202
      return {
        fileUrl: `${JSON.stringify(result)}`
      }
    }
  }
  async updateMsg(ctx) {
    const { id, oldPassword, newPassword, email, nickname, sex, userIntroduce, userPhoto } = ctx.request.body
    let sql = `select * from users where id=${id}`
    let data = await allServices.query(sql).then(async (res) => {
      if (res.length > 0) {
        sql = `update users set ? where id=${id}`
        if (oldPassword) {
          if (res[0].userpwd !== oldPassword) {
            ctx.msg = '旧密码错误'
            ctx.code = 403
            ctx.flag = false
            return false
          } else {
            return await allServices.query(sql, { nickname, userpwd: newPassword, email, sex: sex >= 1 ? 1 : 0, userIntroduce, userPhoto }).then((res) => {
              if (res.affectedRows === 1) {
                ctx.msg = '修改成功'
                return true
              }
            })
          }
        } else {
          return await allServices.query(sql, { nickname, email, sex: sex >= 1 ? 1 : 0, userIntroduce, userPhoto }).then((res) => {
            if (res.affectedRows === 1) {
              ctx.msg = '修改成功'
              return true
            }
          })
        }
      } else {
        ctx.msg = '信息错误'
        ctx.flag = false
        return false
      }
    })
    return data
  }
}

module.exports = new userService();